package com.aierkeji.call.b2c.gson;

import java.lang.reflect.Type;
import java.sql.Timestamp;
import java.util.Date;

import com.aierkeji.call.b2c.util.DateTimeUtils;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;

public class DateTypeAdapter implements JsonSerializer<Date>, JsonDeserializer<Date> {
    @Override
    public Date deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
        if (!(jsonElement instanceof JsonPrimitive)) {
            throw new JsonParseException("The date should be a string value");
        }
        return DateTimeUtils.converStringToDate(jsonElement.getAsString(),DateTimeUtils.DATE_PATTERN_TIMESTAMP);
    }

    @Override
    public JsonElement serialize(Date timestamp, Type type, JsonSerializationContext jsonSerializationContext) {
        return new JsonPrimitive(DateTimeUtils.converDateToString(timestamp,DateTimeUtils.DATE_PATTERN_TIMESTAMP));
    }
}